package com.chatgpt.base.utils;


import java.util.HashMap;
import java.util.Map;

/**
 *
 * 本地线程工具
 * @author yangjian
 *
 */
public final class ThreadLocalUtil {

    private static final ThreadLocal<Map<String, Object>> MAP_THREAD_LOCAL = new ThreadLocal<>();

    private ThreadLocalUtil() {}

    /**
     *
     * 获取当前线程数据
     * @param key 数据键
     * @return 返回数据值
     */
    public static Object getData(String key)
    {
        Map<String, Object> map = MAP_THREAD_LOCAL.get();
        if(null == map){
            return null;
        }
        return map.get(key);
    }

    /**
     *
     * 设置当前线程数据
     * @param key 数据键
     * @param value 数据值
     */
    public static void setData(String key, Object value)
    {
        Map<String, Object> map = MAP_THREAD_LOCAL.get();
        if(null == map){
            synchronized (MAP_THREAD_LOCAL){
                map = MAP_THREAD_LOCAL.get();
                if(null == map){
                    map = new HashMap<>();
                    MAP_THREAD_LOCAL.set(map);
                }
            }
        }
        map.put(key, value);
    }
}
